package com.canbot.u05.activity.dance

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.BaseActivityNoTitle
import com.canbot.u05.activity.customvoice.tool.GridSpacingItemDecoration
import com.canbot.u05.activity.logd
import com.canbot.u05.activity.showToast
import com.canbot.u05.adapter.dance.DanceAdapter
import com.canbot.u05.bean.dance.DanceListInfo
import com.canbot.u05.bean.dance.DanceListItemBean
import com.canbot.u05.bean.dance.ResponseInfo
import com.canbot.u05.network.DanceUtil
import com.canbot.u05.socket.MsgSendUtils
import com.canbot.u05.socket.MsgType
import com.canbot.u05.utils.DisplayUtils
import com.canbot.u05.utils.Logger
import com.canbot.u05.utils.PathConst
import com.canbot.u05.widget.LoadingDialogUtils
import kotlinx.android.synthetic.main.activity_dance_manager.*

/**
 * Created by tao.liu on 2019/6/28.
 * 舞蹈管理界面
 *
 */
class DanceManagerActivity: BaseActivityNoTitle() {
        private val mbrowList: MutableList<DanceListItemBean> = mutableListOf()
        private val constant = 8
        private var homePage: Int = 0
        private var index: Int = 0
        private lateinit var context: Context
        private val tipSound = listOf("wdgl_wdgj_u05_001.mp3","wdgl_wdgj_u05_002.mp3")
        private var dialogLoading: Dialog? = null
        override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
                setContentView(R.layout.activity_dance_manager)
                context = this
                initView()
                dance_viewpager_industry.adapter = pagerAdapter
                dance_viewpager_industry.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                        override fun onPageScrolled(i: Int, v: Float, i1: Int) {}

                        override fun onPageSelected(i: Int) {
                                homePage = i
                                isPress(i)

                        }

                        override fun onPageScrollStateChanged(i: Int) {

                        }
                })
                dance_left.isSelected = true
                dance_right.isSelected = true

        }

        override fun onResume() {
                super.onResume()
                initData()
        }

        /**
         * 初始化数据
         */
        fun initData(){
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this@DanceManagerActivity, resources.getString(R.string.request))
                dialogLoading?.show()
                DanceUtil.queryAllDance(object :DanceUtil.DanceCallBack<DanceListInfo>{
                        override fun onSuccess(result: DanceListInfo) {
                                dialogLoading?.dismiss()
                                 result.let {
                                         if (it.error_code == 0) {
                                                 mbrowList.clear()
                                                 it.content.forEach{
                                                         val imageUrl = if (it.showDefaultImage) it.defaultImage else it.image
                                                         val danceListItemBean = DanceListItemBean(it.id,it.name, imageUrl, it.enabled,it.type) {
                                                                 Log.d(TAG,"点击："+it.name)
                                                                 val intent = Intent(context,DanceDetailActivity::class.java)
                                                                 intent.putExtra("content",JSON.toJSONString(it))
                                                                 startActivity(intent)
                                                                 overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit)
                                                         }
                                                         mbrowList.add(danceListItemBean)
                                                 }
                                         }

                                 }
                                val pageSize = (mbrowList.size + (constant-1)) / constant
                                logd("页数："+pageSize)
                                if (pageSize>1){
                                        dance_left.isSelected = true
                                        dance_right.isSelected = false
                                }else{
                                        dance_left.isSelected = true
                                        dance_right.isSelected = true
                                }
                                val random = (0..1).random()
                                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.PAD_DANCE_TIP_PATH + tipSound[random])
                                pagerAdapter.notifyDataSetChanged()
                        }

                        override fun onFailure() {
                                dialogLoading?.dismiss()
                        }

                })
        }

        fun isPress(homePage: Int) {
                when (homePage) {
                        0 -> {
                                dance_left.isSelected = true
                                dance_right.isSelected = false
                        }
                        (mbrowList.size + (constant-1)) / constant - 1 -> {
                                dance_right.isSelected = true
                                dance_left.isSelected = false
                        }
                        else -> {
                                dance_left.isSelected = false
                                dance_right.isSelected = false
                        }
                }
        }

        private fun initView() {

                btn_back.setOnClickListener {
                        finish()
                        overridePendingTransition(R.anim.face_zoom_enter,
                                R.anim.face_zoom_exit)
                }
                //新建舞蹈
                btn_create_dance.setOnClickListener {
                        startActivity(Intent(this, ChooseMusicActivity::class.java))
                        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit)
                }
                dance_left.setOnClickListener {
                        Logger.e(TAG, "左边按钮")
                        if (dance_viewpager_industry.currentItem == 0) {
                                Logger.e(TAG, "mViewPager.getCurrentItem() = " + dance_viewpager_industry.currentItem)
                                return@setOnClickListener
                        } else {
                                dance_viewpager_industry.setCurrentItem(dance_viewpager_industry.currentItem - 1, true)
                        }
                }
                dance_right.setOnClickListener {
                        Logger.e(TAG, "右边按钮"+ mbrowList.size)
                        if (dance_viewpager_industry.currentItem == pagerAdapter.count - 1) {
                                Logger.e(TAG, "mViewPager.getCurrentItem() = " + dance_viewpager_industry.currentItem)
                                return@setOnClickListener
                        } else {
                                dance_viewpager_industry.setCurrentItem(dance_viewpager_industry.currentItem + 1, true)
                        }
                }
        }

        override fun onPause() {
                super.onPause()
                dialogLoading?.dismiss()
        }
        private val pagerAdapter = object : PagerAdapter() {

                override fun isViewFromObject(arg0: View, arg1: Any): Boolean {

                        return arg0 === arg1
                }

                override fun getCount(): Int {

                        return (mbrowList.size + (constant-1)) / constant
                }

                override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                        container.removeView(`object` as View)
                }

                override fun instantiateItem(container: ViewGroup, position: Int): Any {
                        val inflater = LayoutInflater.from(container.context)
                        val view = inflater.inflate(R.layout.layout_dance_recyclerview, container, false)

                        val mbrowList1 = mbrowList.subList(position * constant, if (position * constant + constant > mbrowList.size) mbrowList.size else position * constant + constant)
                        val recyclerView = view.findViewById<RecyclerView>(R.id.gv_content_action)
                        recyclerView.layoutManager = GridLayoutManager(context, 4)  //网格布局，每行为4
                        recyclerView.addItemDecoration(GridSpacingItemDecoration(4, DisplayUtils.dip2px(context, 24f), false))
                        val actionAdapter = DanceAdapter(context, mbrowList1)
                        recyclerView.adapter = actionAdapter
                        actionAdapter.setIndex(index)
                        container.addView(view)
                        actionAdapter.setDeleteListener {
                                logd("删除舞蹈${homePage*constant+it}")
                                //删除舞蹈
                                DanceUtil.delDance("${mbrowList[homePage*constant+it].id}",object :DanceUtil.DanceCallBack<ResponseInfo>{
                                        override fun onSuccess(result: ResponseInfo) {
                                                if (result.error_code == 0) {
                                                        mbrowList.removeAt(homePage*constant+it)
                                                        notifyDataSetChanged()
                                                }else{
                                                        notifyDataSetChanged()
                                                        showToast("删除失败")
                                                }
                                        }

                                        override fun onFailure() {
                                                notifyDataSetChanged()
                                                showToast("删除失败")
                                        }

                                })

                        }
                        return view
                }

                override fun getItemPosition(`object`: Any): Int {
                        return PagerAdapter.POSITION_NONE
                }
        }

        companion object {
                val TAG = "DanceManagerActivity"
        }
}
